package poi;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

/**
 * This example demonstrates opening a workbook, modifying it and writing
 * the results back out.
 *
 * @author Glen Stampoultzis (glens at apache.org)
 */
public class ReadWriteWorkbook {
    public static void main(String[] args) throws IOException {
        FileInputStream fileIn = null;
        FileOutputStream fileOut = null;
        try
        {
            /**
             * 将Excel文件转为输入流，并构建一个POIFSFileSystem对象
             */
            fileIn = new FileInputStream("D:/testData/sample.xls");
            POIFSFileSystem fs = new POIFSFileSystem(fileIn);

            /**
             * 创建一个workbook，获取Excel表
             */
            HSSFWorkbook workbook = new HSSFWorkbook(fs);
            HSSFSheet sample = workbook.getSheetAt(0);

            /**
             * 读取行1中的数据
             */
            HSSFRow row1 = sample.getRow(0);
            if(row1 != null){

                System.out.println(row1.getCell(2).getStringCellValue());

//                Iterator<Cell> iterator = row1.cellIterator();
//                while(iterator.hasNext()){
//                    Cell nextCell = iterator.next();
//                    System.out.println(nextCell.getStringCellValue());
//                }
            }

            /**
             * 修改Excel表，增加行2，并添加数据
             */
            HSSFRow row2 = sample.getRow(2);
            if (row2 == null)
                row2 = sample.createRow(2);
            HSSFCell cell = row2.getCell(3);
            if (cell == null)
                cell = row2.createCell(3);
            cell.setCellType(CellType.STRING);
            cell.setCellValue("a test");

            // Write the output to a file
            fileOut = new FileOutputStream("D:/testData/sample2.xls");
            workbook.write(fileOut);
        } finally {
            if (fileOut != null)
                fileOut.close();
            if (fileIn != null)
                fileIn.close();
        }
    }
}